package database

import (
	"fmt"
	"log"
	"yoga/config"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

var DB *gorm.DB

// 使用config包的Config连接数据库
func InitDatabase() {
	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable", config.Config.Postgres.Host, config.Config.Postgres.User, config.Config.Postgres.Password, config.Config.Postgres.DBName, config.Config.Postgres.Port)
	var err error
	DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("failed to connect database:", err)
	}
	initUser()
}
func initUser() {
	err := DB.AutoMigrate(&User{})
	if err != nil {
		log.Fatal("failed to migrate database:", err)
	}
	// 生成一个管理员
	user := User{
		UserName: "yang",
		Account:  "yang",
		Password: "3411",
		Auth:     "user",
		Openid:   "admin",
		Gender:   true,
		Age:      20,
		Phone:    "12345678901",
	}
	DB.Create(&user)
	// 生成三个老师
	for i := 0; i < 3; i++ {
		user := User{
			UserName: fmt.Sprintf("teacher%d", i),
			Account:  fmt.Sprintf("teacher%d", i),
			Password: "3411",
			Auth:     "teacher",
			Openid:   fmt.Sprintf("teacher%d", i),
			Gender:   true,
			Age:      20,
			Phone:    "12345678",
		}
		DB.Create(&user)
	}
	// 生成10个学生
	for i := 0; i < 10; i++ {
		user := User{
			UserName: fmt.Sprintf("student%d", i),
			Account:  fmt.Sprintf("student%d", i),
			Password: "3411",
			Auth:     "student",
			Openid:   fmt.Sprintf("student%d", i),
			Gender:   true,
			Age:      20,
			Phone:    "12345678901",
		}
		DB.Create(&user)
	}
}
